package com.ecnu.system.timers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ecnu.common.utils.DateUtils;
import com.ecnu.system.domain.ProjectPlan;
import com.ecnu.system.mapper.ProjectPlanMapper;
import com.ecnu.system.service.IProjectPlanService;
import com.ecnu.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 */
@Component
//@EnableScheduling
public class TimedTask {
    @Autowired
    private IProjectPlanService projectPlanService;
    @Autowired
    private ProjectPlanMapper projectPlanMapper;
    @Autowired
    private ISysDeptService deptService;
    private int count = 0;

    /**
     * 定时更新任务进度
     */
//    @Scheduled(cron = "0 55 23 * * ? ")
    @Scheduled(cron = "0/30 * * * * *  ")
    public void PlanEditProgress() {
        //取出所有手动更新外的项目进度
        List<ProjectPlan> projectPlans = projectPlanMapper.selectList(new QueryWrapper<ProjectPlan>()
                .eq("isManual", "0")
                .eq("del_flag", "0")
                .ne("progress", "100"));
        ArrayList<ProjectPlan> arrayList = new ArrayList<>();
        //获取当前时间
        Date now = new Date();
        for (ProjectPlan projectPlan : projectPlans) {
            ProjectPlan plan = new ProjectPlan();
            //获取开始-结束时间
            Date startTime = projectPlan.getStartTime();
            Date endTime = projectPlan.getEndTime();
            //计算总天数
            Double totalDays = Double.valueOf(DateUtils.differentDaysByMillisecond(startTime, endTime));
            Double remainingDays = Double.valueOf(DateUtils.differentDaysByMillisecond(now,startTime));
            if(now.after(endTime) ){
                remainingDays=totalDays;
            }else if(now.before(startTime)){
                remainingDays=0.0;
            }
            //计算进度
            Double count = (remainingDays / totalDays);
            Integer v =  Math.min(100, (int) (count * 100));

            //设置进度
            plan.setProgress(v);
            plan.setId(projectPlan.getId());
            arrayList.add(plan);
        }
        if (!arrayList.isEmpty()) {
            projectPlanService.updateBatchById(arrayList);
        }

    }


    /**
     * 定时更新部门列表--字典列
     */
//    @Scheduled(cron = "0 0 0 1/2 * ? ")
    public void DeptListProgress() {
        deptService.selectDeptListForExcel();
    }
}
